﻿using System;
using System.Linq;
using MongoDB.Driver;

namespace Order.API.Data
{
    public class OrderContext
    {
        private readonly IMongoClient _mongoClient;
        private readonly IMongoDatabase _mongoDatabase;
        public OrderContext()
        {
            _mongoClient = new MongoClient("mongodb://140.143.88.100:27017");
            if (_mongoDatabase == null)
            {
                _mongoDatabase = _mongoClient.GetDatabase("OrderDb");
            }
        }

        public IMongoCollection<Order.API.Data.AggregatesModel.Order> Orders
        {
            get
            {
                CheckOrCreateCollection(nameof(Order.API.Data.AggregatesModel.Order));
                return _mongoDatabase.GetCollection<Order.API.Data.AggregatesModel.Order>(nameof(Order.API.Data.AggregatesModel.Order));;
            }
        }

        private void CheckOrCreateCollection(string name)
        {
            if (!_mongoDatabase.ListCollectionNames().ToList().Any(n => n.Equals(name)))
            {
                _mongoDatabase.CreateCollection(name);
            }
        }
    }
}
